package com.kk.xhr.admin.biz.impl;

import com.kk.xhr.admin.biz.IUserAuthService;
import com.kk.xhr.admin.controller.request.PasswordModifyRequest;
import com.kk.xhr.admin.controller.request.UserLoginRequest;
import com.kk.xhr.admin.controller.vo.AuthTokenVO;
import com.kk.xhr.common.ErrorCodeEnum;
import com.kk.xhr.common.exception.BusinessException;
import com.kk.xhr.model.entity.User;
import com.kk.xhr.model.service.IUserService;
import com.kk.xhr.web.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 用户认证服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/11
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class UserAuthServiceImpl implements IUserAuthService {
    private final IUserService userService;

    @Override
    public Pair<ErrorCodeEnum, AuthTokenVO> login(UserLoginRequest request) {
        Pair<ErrorCodeEnum, User> userPair = userService.loginByPwd(request.getUsername(), DigestUtils.md5DigestAsHex(request.getPassword().getBytes()));
        switch ((ErrorCodeEnum) userPair.getLeft()) {
            case OK:
                User user = (User)userPair.getRight();
                String token = this.generateJwt(user.getId());
                return Pair.of(ErrorCodeEnum.OK, AuthTokenVO.from(token));
            case USER_NOT_EXIST:
            case PASSWORD_ERROR:
            default:
                return Pair.of(ErrorCodeEnum.LOGIN_FAILED, null);
        }
    }

    @Override
    public void modifyPassword(Long userId, PasswordModifyRequest request) {
        User user = userService.queryUser(userId);
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(request.getOldPassword().getBytes()))) {
            throw new BusinessException(ErrorCodeEnum.PASSWORD_ERROR);
        }
        String mdtPassword = DigestUtils.md5DigestAsHex(request.getNewPassword().getBytes());
        userService.modifyPassword(userId, mdtPassword);
    }

    /**
     * 生成jwt token
     *
     * @param userId 用户id
     * @return token
     */
    private String generateJwt(Long userId) {
        return JwtUtil.sign(String.valueOf(userId));
    }
}
